package de.gist.calldurationwatcher.helper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import de.gist.calldurationwatcher.activities.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.util.Log;

public class Utils {
	
	public static int GetMinutes(long seconds) {
		
		int minutes = (int) (seconds / 60);
		
		if ((seconds / 60.0 - minutes) > 0)
			return minutes + 1;
		
		return minutes;
	}
	
	public static Date GetCallLogFilterDate(Context context) {
		
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
		Calendar cal = Calendar.getInstance();
		int contractDay = preferences.getInt(context.getString(R.string.day_setting), cal.get(Calendar.DAY_OF_MONTH));
		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), contractDay);
		
		if (contractDay > Calendar.getInstance().get(Calendar.DATE))
			cal.add(Calendar.MONTH, -1);
		
		cal.add(Calendar.DATE, -1);
		
		return cal.getTime();
	}
	
	public static boolean IsCallFree(String number, Context context) {
    	
    	try {
    		
    		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    		boolean toAllNetworks = prefs.getBoolean("allNetworks", false);
    		
    		int codeIndex = prefs.getInt("selectedCountry", -1);
    		String[] areaCodesValues =  context.getResources().getStringArray(R.array.areaCodesValues);
    		String country = prefs.getString("countryPreference", null);
    		
    		String landCode = "";
    		if (codeIndex != -1) {
	    		landCode = areaCodesValues[codeIndex];
    		} else if (country != null) {
    			for (int i = 0; i < areaCodesValues.length; i++) {
    				if (areaCodesValues[i].equals(country)) {
    					landCode = country;
    					SharedPreferences.Editor editor = prefs.edit();
    					editor.putInt("selectedCountry", i);
    					editor.commit();
    					break;
    				}
    			}
    		}
    		
    		for (String flatrateode : GetFlatrateAreaCodes(context)) {
				
    			if (flatrateode.trim().length() < 1)
    				continue;
    			
				if (number.startsWith("0") && !number.startsWith("00")) {
					String compareString = flatrateode.substring(flatrateode.lastIndexOf(")") + 1);
					compareString = "0" + compareString;
					if (number.startsWith(compareString))
						return false;
				}
				
				String compareString = flatrateode.replaceAll("\\(0\\)", "");
				compareString = compareString.replace('(', ' ').replace('+', ' ').replace(')', ' ').replaceAll("-", "").replaceAll(" ", "");
				
				if (number.startsWith("+" + compareString) || number.startsWith("00" + compareString) || number.startsWith(compareString))
					return false;
			}
    		
    		if (toAllNetworks) {
    			
    			if (number.startsWith("+" + landCode) || number.startsWith("00" + landCode))
    				return true;
    			
    			if (number.startsWith("0") && !number.startsWith("00" + landCode))
    				return true;
    			
    			if (number.startsWith(landCode))
    				return true;
    			
    			return false;
    		}
    		
	    	for (String areaCode : GetFreeMinutesAreaCodes(context)) {
	    		
	    		if (areaCode.trim().length() < 1)
	    			continue;
	    		
	    		String compareString;
	    		
	    		if (!number.startsWith("0") && number.startsWith(landCode))
	    			number = "+" + number;
	    		
				if (number.startsWith("+") || number.startsWith("00")) {
					
					if (areaCode.startsWith("(")) {
						compareString = areaCode.replaceAll("\\(0\\)", "");
						compareString = compareString.replace('(', ' ').replace('+', ' ').replace(')', ' ').replaceAll("-", "").replaceAll(" ", "");
					} else {
						compareString = areaCode.replaceAll("00", "").replaceAll("-", "").replaceAll(" ", "");
					}
					number = number.replace('+', ' ').replaceAll("00", "").replaceAll("-", "").replaceAll(" ", "");
					
				} else {
					if (!areaCode.startsWith("0"))
						compareString = "0";
					else
						compareString = "";
					compareString = compareString + areaCode.substring(areaCode.lastIndexOf(")") + 1);
					compareString = compareString.replaceAll("-", "").replaceAll(" ", "");
				}
				
				if (number.startsWith(compareString))
					return true;
			}
    	} catch (Exception ex) {
    		Log.e("isCallFree", ex.getMessage());
    	}
    	
    	return false;
    }
	
	public static String JoinAreaCodes(ArrayList<String> savedAreaCodes) {
		
		StringBuffer value = new StringBuffer();
    	for (String code : savedAreaCodes) {
			value.append(code).append(";");
		}
    	
        if (savedAreaCodes.size() > 0 && savedAreaCodes.get(0).length() > 1)
        	return value.toString().substring(0, value.length() - 1);
        else
        	return "";
	}
	
	public static int GetCallLogDuration(Context context) {
		
		int overallDurationMinutes = 0;
		Cursor mCallCursor = CallLogHelper.getCallCursor(context);
    	if (mCallCursor == null)
    		return 0;
    	
    	mCallCursor.moveToFirst();
        while (mCallCursor.isAfterLast() == false) {
        	long duration = mCallCursor.getLong(CallLogFields.DURATION.ordinal());
        	
        	if (IsCallFree(mCallCursor.getString(CallLogFields.NUMBER.ordinal()), context))
        		overallDurationMinutes = overallDurationMinutes + Utils.GetMinutes(duration);
            mCallCursor.moveToNext();
        }
        mCallCursor.close();
        
        return overallDurationMinutes;
	}
	
	public static int GetCallLogNumberDuration(Context context, String number) {
		
		int overallDurationMinutes = 0;
		Cursor mCallCursor = CallLogHelper.getCallCursor(context);
    	if (mCallCursor == null)
    		return 0;
    	
    	mCallCursor.moveToFirst();
        while (mCallCursor.isAfterLast() == false) {
        	
        	String logNumber = mCallCursor.getString(CallLogFields.NUMBER.ordinal());
        	if (!logNumber.startsWith(number)) {
        		mCallCursor.moveToNext();
        		continue;
        	}
        	
        	long duration = mCallCursor.getLong(CallLogFields.DURATION.ordinal());
        	overallDurationMinutes = overallDurationMinutes + Utils.GetMinutes(duration);
            mCallCursor.moveToNext();
        }
        mCallCursor.close();
        
        return overallDurationMinutes;
	}
	
	public static List<String> GetFreeMinutesAreaCodes(Context context) {
	
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		String areaCodesString = prefs.getString(context.getString(R.string.savedAreaCodes), null);
		List<String> savedAreaCodes;
		if (areaCodesString == null)
			savedAreaCodes = new ArrayList<String>();
		else
			savedAreaCodes = Arrays.asList(areaCodesString.split(";"));
		
		return savedAreaCodes;
	}
	
	public static List<String> GetFlatrateAreaCodes(Context context) {
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		String flatrateCodesString = prefs.getString(context.getString(R.string.flatrateAreaCodes), null);
		
		List<String> flatrateAreaCodes;
		
		if (flatrateCodesString == null)
			flatrateAreaCodes = new ArrayList<String>();
		else
			flatrateAreaCodes = Arrays.asList(flatrateCodesString.split(";"));
		
		return flatrateAreaCodes;
	}
}
